package com.fjec.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjec.common.jxls.BreakfastExcel;
import com.fjec.common.util.DateUtil;
import com.fjec.common.view.RpcReturnPage;
import com.fjec.market.entity.InfoMarket;
import com.fjec.market.entity.InfoYsepayRegister;
import com.fjec.market.service.*;
import com.fjec.market.view.ShopVO;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// devops service rpc 调用接口
@RestController
@RequestMapping("")
public class DevOpsController {

    @Autowired
    private IInfoMarketService infoMarketService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private IInfoBusinessService infoBusinessService;

    @Autowired
    private IBizPhysicalOrderService bizPhysicalOrderService;

    @Autowired
    private IInfoYsepayRegisterService infoYsepayRegisterService;

    @GetMapping("/market/devOps/list")
    public Map<String, Object> listMarkets(Page page) {
        Map<String, Object> resultMap = infoMarketService.getDevopsMarkets(page);
        return resultMap;
    }

    // devops保存市场
    @PostMapping("/market/devOps/saveOrUpdate")
    public int saveOrUpdateMarket(@RequestBody InfoMarket infoMarket, @RequestParam String markPic, @RequestParam String markMapPic) {
        infoMarket.setUpdateTime(DateUtil.nowLdt());
        return infoMarketService.saveMarketDevOps(infoMarket, markPic, markMapPic);
    }

    // devops 获取市场详情
    @GetMapping("/market/devOps/getByCode")
    public Map<String, Object> getMarketByMarkCode(int markCode) {
        InfoMarket market = infoMarketService.getOne(new QueryWrapper<InfoMarket>().eq("MarkCode", markCode));
        Map<String, Object> pics = market.getMarkPics();

        ObjectMapper om = new ObjectMapper();
        Map<String, Object> result = om.convertValue(market, Map.class);
        result.put("markPic", pics.get("markPic"));
        result.put("markMapPic", pics.get("markMapPic"));
        result.put("markLoopPics", pics.get("markLoopPics"));
        result.remove("markPics");
        result.remove("createTime");
        result.remove("updateTime");

        return result;
    }

    /**
     * devops 保证金管理
     */
    @GetMapping("/market/deposit/devOps/getDepoInfoByConditions")
    public Map<String, Object> getDepoInfoByConditions(@RequestParam(required = false) Integer searchBy,
                                                       @RequestParam(required = false) String title,
                                                       @RequestParam(required = false) Integer busiType,
                                                       @RequestParam(required = false) Integer markCode,
                                                       @RequestParam(required = false) Integer depoStatus,
                                                       @RequestParam(required = false) Integer timedBy,
                                                       @RequestParam(required = false) String startTime,
                                                       @RequestParam(required = false) String endTime,
                                                       Page page) {
        page.setOptimizeCountSql(false);
        List<Map<String, Object>> data = shopService.getDepoInfoByConditions(searchBy, title, busiType, markCode, depoStatus, timedBy, startTime, endTime, page);
        Long totalDepo = shopService.getTotalDepoByConditions(searchBy, title, busiType, markCode, depoStatus, timedBy, startTime, endTime);
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("totalDepo", totalDepo);
        result.put("total", page.getTotal());
        return result;
    }

    @GetMapping("/market/getBusinessesOfAllTypesByConditions")
    public Map<String, Object> getBusinessesOfAllTypesByConditions(@RequestParam(required = false) Integer searchBy,
                                                                   @RequestParam(required = false) String title,
                                                                   @RequestParam(required = false) Integer busiType,
                                                                   @RequestParam(required = false) Integer markCode,
                                                                   @RequestParam(required = false) String startTime,
                                                                   @RequestParam(required = false) String endTime,
                                                                   Page page) {
        page.setOptimizeCountSql(false);
        page = infoBusinessService.getBusinessesOfAllTypesByConditions(searchBy, title, busiType, markCode, startTime, endTime, page);
        Map<String, Object> result = new HashMap<>();
        result.put("data", page.getRecords());
        result.put("total", page.getTotal());
        return result;
    }

    /**
     * devops 店铺订单列表
     *
     * @param busiId
     * @return
     */
    @GetMapping("/phy/order/getOrdersByBusiId")
    public Map<String, Object> getSubOrdersByBusiId(Long busiId, Page page) {
        List<Map<String, Object>> data = bizPhysicalOrderService.getSubOrdersByBusiId(busiId, page);
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", page.getTotal());
        return result;
    }

    /**
     * devops 按各种条件查询订单列表
     *
     * @param searchBy
     * @param title
     * @param busiType
     * @param markCode
     * @param orderType
     * @param orderStatus
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/phy/order/getOrdersByConditions")
    public Map<String, Object> getOrdersByConditions(@RequestParam(required = false) Integer searchBy,
                                                     @RequestParam(required = false) String title,
                                                     @RequestParam(required = false) Integer busiType,
                                                     @RequestParam(required = false) Integer markCode,
                                                     @RequestParam(required = false) Integer orderType,
                                                     @RequestParam(required = false) Integer orderStatus,
                                                     @RequestParam(required = false) String startTime,
                                                     @RequestParam(required = false) String endTime,
                                                     Page page) {
        page.setOptimizeCountSql(false);
        List<Map<String, Object>> data = bizPhysicalOrderService.getOrderByConditions(searchBy, title, busiType, markCode, orderType, orderStatus, startTime, endTime, page);
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", page.getTotal());
        return result;
    }

    /**
     * 根据子订单Id获取子订单详细
     *
     * @param id
     * @return
     */
    @GetMapping("/phy/order/getOrderDetailById")
    public Map<String, Object> getOrderDetailById(Long id) {
        Map<String, Object> result = bizPhysicalOrderService.getOrderDetailById(id);
        Integer ot = MapUtils.getInteger(result, "orderStatus");
        String orderStatus = "";
        switch (ot) {
            case 1:
                orderStatus = "未付款";
                break;
            case 2:
                orderStatus = "待发货";
                break;
            case 3:
                orderStatus = "待收货";
                break;
            case 4:
                if (StringUtils.isEmpty(MapUtils.getString(result, "ratingId"))) {
                    orderStatus = "待评价";
                } else {
                    orderStatus = "已评价";
                }
                break;
            case 5:
                orderStatus = "已关闭";
                break;
            case 6:
            case 7:
                orderStatus = "发货超时退款";
                break;
            default:
        }
        result.put("orderStatus", orderStatus);
        Integer refundAmount = MapUtils.getInteger(result, "refundAmount");
        if (refundAmount != null)
            result.put("refundAmount", ((double) refundAmount / 100));
        return result;
    }

    @GetMapping("/market/shop/getBusinessInfo")
    public ShopVO getBusinessInfo(Long busiId, Integer busiType) {
        return infoMarketService.getShopIndexById(busiId, busiType);
    }

    @GetMapping("/phy/order/getOrderComplaintsByConditions")
    public Map<String, Object> getOrderComplaintsByConditions(@RequestParam(required = false) Integer searchBy,
                                                              @RequestParam(required = false) String title,
                                                              @RequestParam(required = false) Integer busiType,
                                                              @RequestParam(required = false) Integer markCode,
                                                              @RequestParam(required = false) Integer orderType,
                                                              @RequestParam(required = false) Integer orderStatus,
                                                              @RequestParam(required = false) String startTime,
                                                              @RequestParam(required = false) String endTime,
                                                              Page page) {
        page.setOptimizeCountSql(false);
        List<Map<String, Object>> data = bizPhysicalOrderService.getOrderComplaintsByConditions(searchBy, title, busiType, markCode, orderType, orderStatus, startTime, endTime, page);
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", page.getTotal());
        return result;
    }

    @GetMapping("/market/order/getTradingsByConditions")
    Map<String, Object> getTradingsByConditions(@RequestParam(required = false) Integer searchBy,
                                                @RequestParam(required = false) String title,
                                                @RequestParam(required = false) Integer orderType,
                                                @RequestParam(required = false) Integer sellerType,
                                                @RequestParam(required = false) Integer buyerType,
                                                Page page) {
        List<Map<String, Object>> data = bizPhysicalOrderService.getTradingsByConditions(searchBy, title, orderType, sellerType, buyerType, page);
        data.forEach(d -> {
            Integer ot = MapUtils.getInteger(d, "orderType");
            switch (ot) {
                case 1:
                    d.put("orderType", "零售");
                    break;
                case 2:
                    d.put("orderType", "批采");
                    break;
            }

            Integer buyerBusiType = MapUtils.getInteger(d, "buyerBusiType");
            switch (buyerBusiType) {
                case 1:
                    d.put("buyerBusiType", "个人");
                    break;
                case 2:
                    d.put("buyerBusiType", "果农");
                    break;
                case 3:
                    d.put("buyerBusiType", "分拣厂");
                    break;
                case 4:
                    d.put("buyerBusiType", "农资厂");
                    break;
                case 5:
                    d.put("buyerBusiType", "包装物厂");
                    break;
                case 6:
                    d.put("buyerBusiType", "采购商");
                    break;

                default:
            }

            Integer st = MapUtils.getInteger(d, "sellerShopType");
            switch (st) {
                case 1:
                    d.put("sellerShopType", "个人");
                    break;
                case 2:
                    d.put("sellerShopType", "果农");
                    break;
                case 3:
                    d.put("sellerShopType", "分拣厂");
                    break;
                case 4:
                    d.put("sellerShopType", "农资厂");
                    break;
                case 5:
                    d.put("sellerShopType", "包装物厂");
                    break;
                case 6:
                    d.put("sellerShopType", "采购商");
                    break;

                default:
            }
        });
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", page.getTotal());
        return result;
    }

    @GetMapping("/ys/get/account/info")
    Map<String, Object> getAccountInfo(Long busiId) {
        InfoYsepayRegister register = infoYsepayRegisterService.getOne(new QueryWrapper<InfoYsepayRegister>()
                .eq("BusiId", busiId));
        if (register == null)
            return null;
        Map<String, Object> result = new HashMap<>();
        String accountType = "";
        String custType = register.getCustType();
        if (custType.equals("O"))
            accountType = "个人账户";
        else if (custType.equals("B"))
            accountType = "企业账户";
        else if (custType.equals("C"))
            accountType = "个体账户";
        result.put("accountType", accountType);
        result.put("custName", register.getCustName());
        result.put("legalCertNo", register.getLegalCertNo());
        result.put("bankType", register.getBankType());
        String pc = "";
        pc += register.getBankProvince().get("text");
        pc += register.getBankCity().get("text");
        result.put("pc", pc);
        result.put("bankName", register.getBankName());
        result.put("bankAccountNo", register.getBankAccountNo());
        result.put("bankTelephoneNo", register.getBankTelephoneNo());
        return result;
    }

    @PostMapping("/refund/deposit")
    int refundDeposit(Long busiId, Integer busiType) {
        int code = shopService.refundDeposit(busiId, busiType);
        return code;
    }

    /**
     * 搜索早餐店铺订单信息
     *
     * @param current
     * @param size
     * @param shopId      早餐店铺Id
     * @param subOrderId  子订单Id
     * @param busiType    早餐店铺类型
     * @param orderType   订单类型
     * @param orderStatus 订单状态
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @return
     */
    @GetMapping("/breakfast/get/order/page")
    public RpcReturnPage<Map<String, Object>> rpcGetOrderForBreakfast(@RequestParam long current,
                                                                      @RequestParam long size,
                                                                      @RequestParam(required = false) Long shopId,
                                                                      @RequestParam(required = false) Long subOrderId,
                                                                      @RequestParam(required = false) Integer busiType,
                                                                      @RequestParam(required = false) Integer orderType,
                                                                      @RequestParam(required = false) Integer orderStatus,
                                                                      @RequestParam(required = false) String startTime,
                                                                      @RequestParam(required = false) String endTime) {
        // 计算开始时间和结束时间
        LocalDateTime sTime = null;
        LocalDateTime eTime = null;
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            sTime = LocalDateTime.of(DateUtil.parseLd(startTime, "yyyy-MM-dd"), LocalTime.MIN);
            eTime = LocalDateTime.of(DateUtil.parseLd(endTime, "yyyy-MM-dd"), LocalTime.MAX);
        }
        Page page = new Page(current, size);
        return bizPhysicalOrderService.getOrderForBreakfast(page, shopId, subOrderId, busiType, orderType, orderStatus, sTime, eTime);
    }

    /**
     * 查询早餐店铺订单信息，生成excel用
     *
     * @param shopId
     * @param busiType
     * @param date
     * @return
     */
    @GetMapping("/breakfast/get/order/excel")
    public List<BreakfastExcel> rpcGetOrderForBreakfastExcel(@RequestParam Long shopId,
                                                             @RequestParam Integer busiType,
                                                             @RequestParam String date) {
        // 计算开始时间和结束时间
        LocalDateTime startTime = LocalDateTime.of(DateUtil.parseLd(date, "yyyy-MM-dd"), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(DateUtil.parseLd(date, "yyyy-MM-dd"), LocalTime.MAX);
        return bizPhysicalOrderService.getOrderForBreakfastExcel(shopId, busiType, startTime, endTime);
    }
}
